//
// Created by void on 24-3-17.
//
#include <os/miscellany/date_time.h>
#include <iomanip>
#include <sstream>
namespace iotplat {
    CDateTime::CDateTime(std::time_t time) : time_(time) {
        
    }

    CDateTime CDateTime::FromString(const std::string& timeStr, const std::string& format) {
        std::tm tm{};
        std::istringstream iss(timeStr);
        iss >> std::get_time(&tm, format.c_str());
        return CDateTime(std::mktime(&tm));
    }

    std::string CDateTime::ToString(const std::string& format) const {
        std::tm tm = *std::localtime(&time_);
        std::ostringstream oss;
        oss << std::put_time(&tm, format.c_str());
        return oss.str();
    }

    int CDateTime::GetYear() const {
        std::tm tm = *std::localtime(&time_);
        return tm.tm_year + 1900;
    }

    int CDateTime::GetMonth() const {
        std::tm tm = *std::localtime(&time_);
        return tm.tm_mon + 1;
    }

    int CDateTime::GetDay() const {
        std::tm tm = *std::localtime(&time_);
        return tm.tm_mday;
    }

    void CDateTime::SetYear(int year) {
        std::tm tm = *std::localtime(&time_);
        tm.tm_year = year - 1900;
        time_ = std::mktime(&tm);
    }

    void CDateTime::SetMonth(int month) {
        std::tm tm = *std::localtime(&time_);
        tm.tm_mon = month - 1;
        time_ = std::mktime(&tm);
    }

    void CDateTime::SetDay(int day) {
        std::tm tm = *std::localtime(&time_);
        tm.tm_mday = day;
        time_ = std::mktime(&tm);
    }

    bool CDateTime::IsSameDate(const CDateTime& other) const {
        std::tm tm1 = *std::localtime(&time_);
        std::tm tm2 = *std::localtime(&other.time_);
        return tm1.tm_year == tm2.tm_year && tm1.tm_mon == tm2.tm_mon && tm1.tm_mday == tm2.tm_mday;
    }

    CDateTime CDateTime::AddDays(int days) const {
        std::tm tm = *std::localtime(&time_);
        tm.tm_mday += days;
        return CDateTime(std::mktime(&tm));
    }

    std::time_t CDateTime::GetTime() const {
        return time_;
    }

    void CDateTime::SetTime(std::time_t time) {
        time_ = time;
    }

    CDateTime CDateTime::Now() {
        return CDateTime(std::time(nullptr));
    }
}
